package com.wanli.storemobile.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.view.KeyEvent;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.gyf.immersionbar.ImmersionBar;
import com.wanli.storemobile.R;
import com.wanli.storemobile.appconst.Constants;
import com.wanli.storemobile.utils.ActivityUtil;
import com.wanli.storemobile.utils.UIAdapterUtils;
import com.wanli.storemobile.widget.NetBroadcastReceiver;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public abstract class BaseActivity extends AppCompatActivity {
    private NetBroadcastReceiver networkChangReceiver;
    public Activity mActivity;
    private static final String TAG = BaseActivity.class.getSimpleName();
    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mActivity = this;
        handlerOrientation();
        super.onCreate(savedInstanceState);
        UIAdapterUtils.setCustomDensity(this, this.getApplication());//今日头条屏幕适配方案
        ActivityUtil.getInstance().addActivity(this); // 添加到Activity工具类

        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(false, 0.2f)
                .init();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.ON_AFTER_RELEASE | PowerManager.PARTIAL_WAKE_LOCK, "Tag");
    }


    public boolean isDestroy() {
        boolean isDestroy = false;
        if (mActivity == null || mActivity.isFinishing()) {
            isDestroy = true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (isDestroyed()) {
                isDestroy = true;
            }
        }
        return isDestroy;
    }

    @Override
    protected void onResume() {
        if (wakeLock != null) {
            wakeLock.acquire();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (wakeLock != null) {
            wakeLock.release();
        }
        super.onPause();
    }

    /**
     * 安卓8.0版本时为了支持全面屏，增加了一个限制：
     * 如果是透明的Activity，则不能固定它的方向，因为它的方向其实是依赖其父Activity的（因为透明）。
     * 然而这个bug只有在8.0中有，8.1中已经修复。具体crash有两种：
     */
    private void handlerOrientation() {

        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {//透明
            boolean result = fixOrientation();
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 设置竖屏
        }
    }

    private boolean isTranslucentOrFloating() {
        boolean isTranslucentOrFloating = false;
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean) m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

    private boolean fixOrientation() {
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo) field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityUtil.getInstance().removeActivity(this); // 移除Activity
        unRegisterEventBus();
    }


    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
    }


    /**
     * 注册网路监听
     */
    public void registerNetWork() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        networkChangReceiver = new NetBroadcastReceiver();
        registerReceiver(networkChangReceiver, intentFilter);
    }

    /**
     * 注册EventBus
     */
    public void registerEventBus() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    public void unRegisterEventBus() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);  //注销eventbus
        }
    }

    public void unRegisterNetWork() {
        unregisterReceiver(networkChangReceiver); //注销eventbus
    }


    /**
     * 权限检查方法，false代表没有该权限，ture代表有该权限
     */
    public boolean hasPermission(String... permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 沉浸式状态栏
     * 当XML 设置android:fitsSystemWindows="true"时 沉浸式失效
     */
    public void setImmersionStatusBar(BaseActivity activity) {
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//沉浸式状态栏
    }

    /**
     * @param activity : 将要被显示的Activity
     * @param data     ： extraData
     */
    public void showActivity(Class<? extends BaseActivity> activity, Bundle data) {
        Intent intent = new Intent(this, activity);
        if (data != null) {
            intent.putExtras(data);
        }
        startActivity(intent);
    }

    @Override
    public void finish() {
        super.finish();
    }

    /**
     * @param activity : 将要被显示的Activity
     */
    public void showActivity(Class<? extends BaseActivity> activity) {
        showActivity(activity, null);
    }

    /**
     * 处理权限
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.PERMISSION_REQUEST_CODE) {
            try {
                handlerPermissionForActivityResult();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return;
        }
    }

    public void handlerPermissionForActivityResult() throws Exception {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }


    /**
     * 是否登录
     */
//    public boolean isNeedLogin() {
//        String token = SPManager.getInstance().getToken();
//        Intent intent = null;
//        if (TextUtils.isEmpty(token)) {
//            intent = new Intent(this, MobileLoginActivity.class);
//            startActivity(intent);
//            return true;
//        }
//        return false;
//    }
}
